package com.gdit.zax.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gdit.zax.Constant;
import com.gdit.zax.dao.DynamicDao;
import com.gdit.zax.dao.UserDao;
import com.gdit.zax.entitys.UserInfo;
import com.gdit.zax.factory.DAOFactory;
import com.gdit.zax.utils.DBUtil;
import com.gdit.zax.utils.LogUtil;
import com.gdit.zax.utils.MD5;
import com.gdit.zax.utils.SqlUtil;
import com.gdit.zax.utils.VeriFicUtil;
import com.gdit.zax.utils.webUtil;
//
public class UserDaoImpl implements UserDao {

	private PreparedStatement ps;
	private ResultSet rs;
	
	private Connection conn;
	private HttpServletRequest request;
	private HttpServletResponse response;
	
	
	public UserDaoImpl(Connection conn,HttpServletRequest request, HttpServletResponse response) {
		this.conn = conn;
		this.request = request;
		this.response = response;
	}
	
	public boolean isRegister(int sid,String name) {
		String sql = "select * from t_user where UserName=? and SchoolId in (-1,?)";
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, name);
			ps.setInt(2, sid);
			
			rs = ps.executeQuery();
			
			if (rs.next()){
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public boolean bindPlatform(String accesstoken, int where, String ptoken) {
		// TODO Auto-generated method stub
		return false;
	}

	public UserInfo loginByPlatform(int where, String token) {
		// TODO Auto-generated method stub
		return null;
	}

	public boolean register(UserInfo info) {
		if (isRegister(info.getSchoolid(), info.getUsername())) {
			return false;
		}
		try {
			String sql = "insert t_user set UserName=?,Password=?,Email=?,Sex=?,Age=?,UserHead=?,SchoolId=?";
			ps = conn.prepareStatement(sql);
			ps.setString(1, info.getUsername());
			ps.setString(2, info.getPassword());
			ps.setString(3,info.getEmail());
			ps.setInt(4, info.getSex());
			ps.setInt(5, info.getAge());
			ps.setString(6, info.getUserhead());
			ps.setInt(7, info.getSchoolid());
			
			int result = ps.executeUpdate();
			if (result!=0) {
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}


//	public UserInfo login(String name, String pwdmd5, int logintype) {
//		String ip = request.getRemoteHost();
//		String device = request.getHeader("user-agent");
//		if (device.length()>255) {
//			device = device.replace(" ", "").substring(0, 255);
//		}
//		
//		
//		UserInfo info = verification(name,pwdmd5);
//		if (info!=null) {
//			String loginkey = MD5.getMD5(info.getId() + "," + System.currentTimeMillis());
//			try {
//				String sql;
//				if (logintype == Constant.LOGINTYPE_APP) {
//					sql = "update t_user set Accesstoken=?,logintime=now() where Id=?";	
//				} else if (logintype == Constant.LOGINTYPE_WEB) {
//					sql = "update t_user set LoginCookie=?,logintime=now() where Id=?";
//				} else {
//					sql = "update t_user set LoginFlag=?,logintime=now() where Id=?";
//				}
//				ps = conn.prepareStatement(sql);
//				ps.setString(1, loginkey);
//				ps.setInt(2, info.getId());
//				
//				int result=ps.executeUpdate();
//				if (result!=0) {
//					sql = "insert t_login set Device=?,System=?,UserId=?,Ip=?";	
//					ps = conn.prepareStatement(sql);
//					ps.setString(1, device);
//					ps.setString(2, device);
//					ps.setInt(3, info.getId());
//					ps.setString(4, ip);
//					ps.executeUpdate();//插入登录信息
//					
//					if (logintype == Constant.LOGINTYPE_APP) {
//						info.setAccesstoken(loginkey);
//					} else if (logintype == Constant.LOGINTYPE_WEB) {
//						info.setLogincookie(loginkey);
//					} else {
//						info.setLoginflag(loginkey);
//					}
//				}
//			}catch (Exception e) {
//				e.printStackTrace();
//			}
//			
//		}
//		return info;
//	}

	
	/**
	 * 验证账号密码
	 */
	public UserInfo verification(int sid,String name, String pwdmd5) {
		UserInfo info = null;
		String sql = "select * from t_user where UserName=? and Password=? and SchoolId in (-1,?)";
		//-1是管理员，可以登陆任意学校
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, name);
			ps.setString(2, pwdmd5);
			ps.setInt(3, sid);
			rs = ps.executeQuery();
			
			while(rs.next()){
				info = DBUtil.getobject(rs, UserInfo.class);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return info;
	}

	public UserInfo getInfo(int logintype, String token) {
		UserInfo info = null;
		String sql;
		if (logintype==Constant.LOGINTYPE_APP) {
			sql = "select * from t_user where Accesstoken=?";
		} else if (logintype==Constant.LOGINTYPE_WEB) {
			sql = "select * from t_user where LoginCookie=?";
		} else {
			sql = "select * from t_user where LoginFlag=?";
		}
		
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, token);
			rs = ps.executeQuery();
			
			while(rs.next()){
				info = DBUtil.getobject(rs, UserInfo.class);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return info;
	}

	public boolean updataInfo(UserInfo info) {
		return DBUtil.saveobject(conn, "t_user", "id = " + info.getId(), info);
	}

	public int getRegisterId() {
		try {
			String sql = "select * from t_user group by Id desc limit 0,1";
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			while(rs.next()){
				UserInfo info = DBUtil.getobject(rs, UserInfo.class);
				if (info!=null) {
					return info.getId()+1;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return 0;
	}

	
	

	public UserInfo getInfo(int uid) {
		try {
			String sql = "select * from t_user where Id=?";

			ps = conn.prepareStatement(sql);
			ps.setInt(1, uid);
			
			rs = ps.executeQuery();
			
			if (rs.next()){
				return DBUtil.getobject(rs, UserInfo.class);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public UserInfo login(int sid, String name, String pwdmd5,String system,String device, int logintype) {
		String ip  = webUtil.getIpAddr(request);
		if (system.length()>255) {
			system = system.replace(" ", "").substring(0, 255);
		}
		if (device.length()>255) {
			device = device.replace(" ", "").substring(0, 255);
		}
		
		UserInfo info = verification(sid,name,pwdmd5);
		if (info!=null) {
			String loginkey = "";
			try {
				String sql;
				if (logintype == Constant.LOGINTYPE_APP) {
					loginkey = VeriFicUtil.getIDVF(info.getId());
					sql = "update t_user set Accesstoken=?,logintime=now() where Id=?";	
				} else if (logintype == Constant.LOGINTYPE_WEB) {
					loginkey = MD5.getMD5(info.getId() + "," + System.currentTimeMillis());
					sql = "update t_user set LoginCookie=?,logintime=now() where Id=?";
				} else {
					loginkey = MD5.getMD5(info.getId() + "," + System.currentTimeMillis());
					sql = "update t_user set LoginFlag=?,logintime=now() where Id=?";
				}
				ps = conn.prepareStatement(sql);
				ps.setString(1, loginkey);
				ps.setInt(2, info.getId());
				
				int result=ps.executeUpdate();
				if (result!=0) {
					sql = "insert t_login set Device=?,System=?,UserId=?,Ip=?";	
					ps = conn.prepareStatement(sql);
					ps.setString(1, device);
					ps.setString(2, system);
					ps.setInt(3, info.getId());
					ps.setString(4, ip);
					ps.executeUpdate();//插入登录信息
					
					if (logintype == Constant.LOGINTYPE_APP) {
						info.setAccesstoken(loginkey);
					} else if (logintype == Constant.LOGINTYPE_WEB) {
						info.setLogincookie(loginkey);
					} else {
						info.setLoginflag(loginkey);
					}
				}
			}catch (Exception e) {
				e.printStackTrace();
			}
			
		}
		return info;
	}

	public boolean addscore(int uid,int score) {
		String sql = "update t_user set Score=Score+? where Id=?";
		try {

			ps = conn.prepareStatement(sql);
			ps.setInt(1, score);
			ps.setInt(2, uid);
			
			int result = ps.executeUpdate();
			if (result!=0) {
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public int getDoneCourseSum(int uid) {
		String sql = SqlUtil.getSql("getUserDoneCourseSum.sql");
		try {
			ps = conn.prepareStatement(sql);
			ps.setInt(1, uid);
			ps.setInt(2, uid);
			
			rs  = ps.executeQuery();
			if (rs.next()) {
				return rs.getInt(1);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 0;
	}

	public UserInfo getInfobyEmail(String uname, String email) {
		String sql = "select * from t_user where UserName=? and Email=?";
		try {

			ps = conn.prepareStatement(sql);
			ps.setString(1, uname);
			ps.setString(2, email);
			
			rs = ps.executeQuery();
			if (rs.next()) {
				return DBUtil.getobject(rs, UserInfo.class);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public UserInfo getInfobyPhone(String uname, String phone) {
		// TODO Auto-generated method stub
		return null;
	}

	public boolean addUser(UserInfo uinfo) {
		String sql = "insert t_user set Password=?,SchoolId=?,UserName=?,Nick=?,Sex=?,Age=?,Phone=?,Address=?";
		//数据库md5=MD5.getMD5(MD5.getMD5(username + MD5.getMD5(pwd)))
//		uinfo.setUsername(uinfo.getUsername()==null?"N":uinfo.getUsername());
//		uinfo.setPhone(uinfo.getPhone()==null?"N":uinfo.getPhone());
//		uinfo.setAddress(uinfo.getAddress()==null?"N":uinfo.getAddress());
//		uinfo.setNick(uinfo.getNick()==null?"N":uinfo.getNick());
		
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, MD5.getMD5(MD5.getMD5(uinfo.getUsername() + MD5.getMD5(uinfo.getPassword()))));
			ps.setInt(2, uinfo.getSchoolid());
			ps.setString(3, uinfo.getUsername());
			ps.setString(4, uinfo.getNick());
			ps.setInt(5, uinfo.getSex());
			ps.setInt(6, uinfo.getAge());
			long phone = 0;
			try {
				phone = Long.parseLong(uinfo.getPhone());
			} catch (Exception e) {
			}
			ps.setLong(7, phone);	
			ps.setString(8, uinfo.getAddress());
			
			
			int result = ps.executeUpdate();
			if (result!=0) {
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return false;
	}

	public List<UserInfo> listUser(int page, int onepagecount) {
		String sql = "select * from t_user limit ?,?";
		List<UserInfo>  list = new ArrayList<UserInfo>();
		try {
			ps = conn.prepareStatement(sql);
			ps.setInt(1, (page-1)*onepagecount);
			ps.setInt(2, onepagecount);
			
			rs = ps.executeQuery();
			while (rs.next()) {
				list.add(DBUtil.getobject(rs, UserInfo.class));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	public boolean setDBuserId(int uid, String dbid) {
		String sql = "update t_user set DBUserId=? where Id=?";	
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, dbid);
			ps.setInt(2, uid);
			
			int re = ps.executeUpdate();
			if (re > 0) {
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return false;
	}


//	public UserInfo loginByApp(String name, String pwd) {
//		UserInfo info = verification(name,pwd);
//		if (info!=null) {
//			String accesstoken = MD5.getMD5("" + info.getId() + new Date().getTime());
//			try {
//				String sql = "update t_user set Accesstoken=? where Id=?";
//				ps = conn.prepareStatement(sql);
//				ps.setString(1, accesstoken);
//				ps.setInt(2, info.getId());
//				rs = ps.executeQuery();
//				
//				int result=ps.executeUpdate();
//				if (result!=0) {
//					info.setAccesstoken(accesstoken);
//				}
//			}catch (Exception e) {
//				e.printStackTrace();
//			}
//			
//		}
//		return info;
//	}
//
//	public UserInfo loginByWeb(String name, String pwd) {
//		UserInfo info = verification(name,pwd);
//		if (info!=null) {
//			String logincookie = MD5.getMD5("" + info.getId() + new Date().getTime());
//			try {
//				String sql = "update t_user set LoginCookie=? where Id=?";
//				ps = conn.prepareStatement(sql);
//				ps.setString(1, logincookie);
//				ps.setInt(2, info.getId());
//				rs = ps.executeQuery();
//				
//				int result=ps.executeUpdate();
//				if (result!=0) {
//					info.setLogincookie(logincookie);
//				}
//			}catch (Exception e) {
//				e.printStackTrace();
//			}
//			
//		}
//		return info;
//	}
	
	
}
